import $ajax from '../helper/ajax'
import {
  adUrl,
  adConfig,
  channelUrl,
  hlAdLogUrl,
  pkgChannel,
  appSource,
  downloadAdUrl
} from '../helper/config'
import utils from './utils'
import md5 from 'crypto-js/md5'
import hash from 'crypto-js/sha256'
import { setGlobalData, getGlobalData } from '../global'
import systemDevice from '@system.device'
import manifest from '../manifest.json'
/**
 * @desc 在实际开发中，您可以将 baseUrl 替换为您的请求地址前缀；
 *
 * 已将 $apis 挂载在 global，您可以通过如下方式，进行调用：
 * $apis.example.getApi().then().catch().finally()
 *
 */
export default {
  // et15:每次拉起都上报后端 et16:应用打开上报后端
  async addReported(et = 15, extraData = {}) {
    const time = Number(new Date())
    const deviceInfo =
      getGlobalData('deviceInfo') || (await $utils.getDeviceInfo())
    const { brand, osVersionCode, osVersionName, model } = deviceInfo
    const idInfo = getGlobalData('idInfo') || (await $utils.getId())
    const { mac, device, user } = idInfo
    let adchannel = getGlobalData('adchannel') || {}
    const { od, odMd5, azem, azemMd5 } = this.getDeviceObj(
      osVersionName,
      device
    )
    const fingerprint = odMd5 || (user ? md5(user).toString() : 'nyK')
    const params = {
      et: et, //应用拉起
      union_site: adchannel?.aidReportChannel || '', //归因渠道---可选

      app_source: appSource, //app来源
      channel: pkgChannel, //渠道
      appver: manifest.versionCode, //app 版本
      brand: brand, //品牌
      os: 0, //操作系统
      osver: osVersionCode, //操作系统版本号
      azem: azemMd5 || '', //imei mad5值---可选
      od: odMd5 || '', //oaid md5值
      azidm: user ? md5(user).toString() : '', //androidld md5值---可选
      did: user || '', //设备deviceid
      mcm: mac ? mac.split(':').join('') : '', //设备mac地址
      wz: '',
      pig: '',
      ml: model, //设备型号
      network: '',
      carrier: '',
      ts: time, //数据上报时间
      uua: '',
      uid: '',
      fingerprint,
      aid: adchannel?.aid || '',
      adv_id: adchannel?.advId || '',
      ca_id: adchannel?.caId || '',
      cid: adchannel?.cid || '',
      agency: adchannel?.agency || '',
      ...extraData
    }
    return $ajax.get(`${adUrl}`, params, { tag: 'ad', auth: false })
  },
  //上报接口
  adReport(data) {
    const time = Number(new Date())
    const { brand, osVersionCode, osVersionName, model } = getGlobalData(
      'deviceInfo'
    )
    const { mac, device, user } = getGlobalData('idInfo')
    let adchannel = getGlobalData('adchannel')
    const { od, odMd5, azem, azemMd5 } = this.getDeviceObj(
      osVersionName,
      device
    )
    const fingerprint = odMd5 || (user ? md5(user).toString() : 'nyK')
    const params = {
      app_source: appSource,
      did: getGlobalData('androidId'),
      fingerprint,
      channel: pkgChannel,
      appver: manifest.versionCode, //app 版本
      brand: brand,
      os: 0,
      osver: osVersionCode,
      mcm: mac ? mac.split(':').join('') : '',
      ts: time,
      //azem加密、od加密
      azem: azemMd5 || '',
      od: odMd5 || '',
      azidm: user ? md5(user).toString() : '',
      ml: model,

      // 广告请求记录
      et: 10,
      bt_id: '',
      report_type: '',
      bt_pname: '',
      bt_pid: '',
      source: '',
      wz: '',
      union_site: adchannel?.aidReportChannel || '',
      aid: adchannel?.aid || '',
      adv_id: adchannel?.advId || '',
      ca_id: adchannel?.caId || '',
      cid: adchannel?.cid || '',
      agency: adchannel?.agency || '',
      ...data
    }
    return $ajax.get(`${adUrl}`, params, { tag: 'ad', auth: false })
  },
  //渠道标识（hap-标签匹配)-新版
  getLaunchHap() {
    const time = Number(new Date())
    const { brand, osVersionCode, osVersionName, model } =
      getGlobalData('deviceInfo') || {}
    const { mac, device, user } = getGlobalData('idInfo') || {}
    const { oaid } = getGlobalData('oaid') || {}
    const { od, odMd5, azem, azemMd5 } = this.getDeviceObj(
      osVersionName,
      device
    )
    const publicParams = getGlobalData('publicParams') || {}
    console.log('getLaunchHap-mutual', getGlobalData('mutual'))
    const adPlatform = publicParams?.ad_platform || ''
    let advId =
      adPlatform == '52' ? publicParams?.corp_id : publicParams?.adv_id
    let aid = adPlatform == '52' ? publicParams?.campaign_id : publicParams?.aid
    let aidName =
      adPlatform == '52' ? publicParams?.campaign_name : publicParams?.aid_name
    let cid = adPlatform == '52' ? publicParams?.content_id : publicParams?.cid
    let requestId =
      adPlatform == '52'
        ? publicParams?.transunique_id
        : publicParams?.request_id
    let extraPlatform = {}
    if (adPlatform == '61') {
      extraPlatform.logExtra = publicParams?.logExtra
      extraPlatform.conversionId = publicParams?.conversionId
      extraPlatform.webConversionId = publicParams?.webConversionId
    }
    const quickAppVer = systemDevice?.host?.versionCode || ''
    let rType =
      getGlobalData('mutual') == 1 ? getGlobalData('rtypeChannel') + '-la' : ''
    const callback = publicParams.callback || ''
    if (adPlatform == '42') {
      const tid = publicParams.tid || ''
      requestId = encodeURIComponent(tid)
    }
    const fingerprint = odMd5 || (user ? md5(user).toString() : 'nyK')
    const params = {
      appSource: appSource,
      appver: manifest.versionCode,
      quickAppVer: quickAppVer,
      channel: pkgChannel,
      fingerprint,
      pkg: manifest.package,
      brand: brand,
      mc: mac ? mac.split(':').join('') : '',
      ts: time,
      //公参
      wap: publicParams?.wap || '',
      caid1: publicParams?.caid1 || '',
      adPlatform: adPlatform,
      unionSite: publicParams?.channel || '',
      advId: advId || '',
      aidName: aidName || '',
      aid: aid || '',
      cid: cid || '',
      ml: model,
      imei: azem || publicParams?.imei || '',
      imeiMd5: azemMd5 || publicParams?.imei_sum || '',
      ip: publicParams?.ip || '',
      requestId: requestId || '',
      oaid: od || publicParams?.oaid || '',
      oaidMd5: odMd5 || publicParams?.oaid_sum || '',
      uua: publicParams?.uua || '',
      deviceId: user || publicParams?.device_id || '',
      deviceIdMd5:
        (user && md5(user).toString()) || publicParams?.device_id_sum || '',
      azidm: user ? md5(user).toString() : '',
      callback: encodeURIComponent(callback) || '',
      callbackParam: publicParams?.cb_par || '',
      clickId: publicParams?.click_id || '',
      caId: publicParams?.adgroup_id || '',
      dpLink: '', //暂时传空
      fromPkg: getGlobalData('appSource') || '',
      rType: rType,
      agency: publicParams?.agency || '',
      pageId: publicParams?.pageId || '',
      lbid: publicParams?.lbid || '',
      appId: publicParams?.appId || '',
      ...extraPlatform
    }
    return $ajax.post(`${channelUrl}/attribution/quickApp`, params, {
      auth: false
    })
  },
  //转化事件
  gethlAdLog(data) {
    const { device, user, mac } = getGlobalData('idInfo') || {}
    const { brand, model, osVersionName } = getGlobalData('deviceInfo') || {}
    const { event } = data
    const { od, odMd5, azem, azemMd5 } = this.getDeviceObj(
      osVersionName,
      device
    )
    const fingerprint = odMd5 || (user ? md5(user).toString() : 'nyK')
    const params = {
      appSource: appSource,
      appver: manifest.versionCode,
      channel: pkgChannel,
      fingerprint,
      // od原值、azem 加密
      od: od ? od : '',
      azem: azemMd5 ? azemMd5 : '',
      azid: user ? md5(user).toString() : '',
      pig: '',
      os: 0,
      uua: '',
      event: event,
      ts: Number(new Date()),
      ml: brand + model,
      mc: mac ? mac.split(':').join('') : '',
      muid: '',
      uid: '',
      blackBox: '',
      appType: '',
      atUuid: '',
      sign: ''
    }
    return $ajax.get(`${hlAdLogUrl}/hlAdLog/report`, params, { auth: false })
  },
  //广告配置--新版
  getAdConfig(data) {
    const { aidReportChannel } = data
    const { osVersionName } = getGlobalData('deviceInfo') || {}
    const { mac, device, user } = getGlobalData('idInfo') || {}
    const { oaid } = getGlobalData('oaid') || {}
    const { od, odMd5, azem, azemMd5 } = this.getDeviceObj(
      osVersionName,
      device
    )
    const fingerprint = odMd5 || (user ? md5(user).toString() : 'nyK')
    const params = {
      channel: pkgChannel,
      appSource: appSource,
      appVersion: manifest.versionCode,
      deviceId: user || '',
      fingerprint,
      // imei加密、oaid 加密
      imei: azemMd5 || '',
      oaid: odMd5 || '',
      androdid: user || '',
      mac: mac || '',
      os: 0,
      aidReportChannel: aidReportChannel || ''
    }
    return $ajax.get(`${adConfig}/v1/luck/load`, params, { auth: false })
  },
  getDeviceObj(osVersionName, device) {
    let deviceObj = {}
    let oaidObj = getGlobalData('oaid')
    let oaid = oaidObj?.oaid
    if (oaid && oaid != '') {
      deviceObj = {
        od: oaid,
        odMd5: md5(oaid).toString()
      }
    } else {
      // 取device 安卓版本>=10传od 否则传azem
      if (osVersionName >= 10) {
        deviceObj = {
          od: device,
          odMd5: device ? md5(device).toString() : device
        }
      } else {
        deviceObj = {
          azem: device,
          azemMd5: device ? md5(device).toString() : device
        }
      }
    }
    return deviceObj
  },
  // 用户归因与广告配置 https://doc.ntyy888.com/web/#/5/393
  matchAcquire() {
    const time = Number(new Date())
    const { brand, osVersionCode, osVersionName, model } =
      getGlobalData('deviceInfo') || {}
    const { mac, device, user } = getGlobalData('idInfo') || {}
    const { oaid } = getGlobalData('oaid') || {}
    const { od, odMd5, azem, azemMd5 } = this.getDeviceObj(
      osVersionName,
      device
    )
    const publicParams = getGlobalData('publicParams') || {}
    console.log('getLaunchHap-mutual', getGlobalData('mutual'))
    const adPlatform = publicParams?.ad_platform || ''
    let advId =
      adPlatform == '52' ? publicParams?.corp_id : publicParams?.adv_id
    let aid = adPlatform == '52' ? publicParams?.campaign_id : publicParams?.aid
    let aidName =
      adPlatform == '52' ? publicParams?.campaign_name : publicParams?.aid_name
    let cid = adPlatform == '52' ? publicParams?.content_id : publicParams?.cid
    let requestId =
      adPlatform == '52'
        ? publicParams?.transunique_id
        : publicParams?.request_id
    let extraPlatform = {}
    if (adPlatform == '61') {
      extraPlatform.logExtra = publicParams?.logExtra
      extraPlatform.conversionId = publicParams?.conversionId
      extraPlatform.webConversionId = publicParams?.webConversionId
    }
    const quickAppVer = systemDevice?.host?.versionCode || ''
    let rType =
      getGlobalData('mutual') == 1 ? getGlobalData('rtypeChannel') + '-la' : ''
    const callback = publicParams.callback || ''
    if (adPlatform == '42') {
      const tid = publicParams.tid || ''
      requestId = encodeURIComponent(tid)
    }
    const fingerprint = odMd5 || (user ? md5(user).toString() : 'nyK')
    const params = {
      appSource: appSource,
      appver: manifest.versionCode,
      quickAppVer: quickAppVer,
      channel: pkgChannel,
      fingerprint,
      pkg: manifest.package,
      brand: brand,
      mc: mac ? mac.split(':').join('') : '',
      ts: time,
      //公参
      wap: publicParams?.wap || '',
      caid1: publicParams?.caid1 || '',
      adPlatform: adPlatform,
      unionSite: publicParams?.channel || '',
      advId: advId || '',
      aidName: aidName || '',
      aid: aid || '',
      cid: cid || '',
      ml: model,
      imei: azem || publicParams?.imei || '',
      imeiMd5: azemMd5 || publicParams?.imei_sum || '',
      ip: publicParams?.ip || '',
      requestId: requestId || '',
      oaid: od || publicParams?.oaid || '',
      oaidMd5: odMd5 || publicParams?.oaid_sum || '',
      uua: publicParams?.uua || '',
      deviceId: user || publicParams?.device_id || '',
      deviceIdMd5:
        (user && md5(user).toString()) || publicParams?.device_id_sum || '',
      azidm: user ? md5(user).toString() : '',
      callback: encodeURIComponent(callback) || '',
      callbackParam: publicParams?.cb_par || '',
      clickId: publicParams?.click_id || '',
      caId: publicParams?.adgroup_id || '',
      dpLink: '', //暂时传空
      fromPkg: getGlobalData('appSource') || '',
      rType: rType,
      agency: publicParams?.agency || '',
      pageId: publicParams?.pageId || '',
      lbid: publicParams?.lbid || '',
      appId: publicParams?.appId || '',
      ...extraPlatform
    }
    return $ajax.post(`${channelUrl}/match/quick/acquire`, params, {
      auth: false
    })
  },
  //激活列表
  getActiveJson(url) {
    return $ajax.get(url, {}, { auth: false })
  },
  downloadAdText(extraData = {}) {
    const { osVersionName } = getGlobalData('deviceInfo') || {}
    const { mac, device, user } = getGlobalData('idInfo') || {}
    const { od, odMd5, azem, azemMd5 } = this.getDeviceObj(
      osVersionName,
      device
    )
    const key = '34qkgnggvdfg@Q#@#YUR323hrwh'
    const reqtime = new Date().getTime()
    const nonce = utils.getRandomString(6)
    const fingerprint = odMd5 || (user ? md5(user).toString() : 'nyK')
    const sign = hash(fingerprint + reqtime + nonce + key).toString()
    const signSlice = sign.substr(10, 10)
    return $ajax
      .get(
        `${downloadAdUrl}/auth/download.json`,
        // 'https://20230712.oss-cn-hangzhou.aliyuncs.com/ad-v2.js',
        // 'https://20230712.oss-cn-hangzhou.aliyuncs.com/ad-encode-v2.txt',
        {
          filename: 'ad-encode-v3.txt',
          appSource,
          ...extraData
        },
        {
          reqtime,
          nonce,
          fingerprint,
          sign: signSlice,
          auth: false,
          tag: 'direct'
        }
      )
      .then(res => {
        // console.log(utils.encrypt(res).toString())
        // return res
        return utils.decrypt(res).toString()
      })
  },
  downloadAdStyle(extraData = {}) {
    const { osVersionName } = getGlobalData('deviceInfo') || {}
    const { mac, device, user } = getGlobalData('idInfo') || {}
    const { od, odMd5, azem, azemMd5 } = this.getDeviceObj(
      osVersionName,
      device
    )
    const key = '34qkgnggvdfg@Q#@#YUR323hrwh'
    const reqtime = new Date().getTime()
    const nonce = utils.getRandomString(6)
    const fingerprint = odMd5 || (user ? md5(user).toString() : 'nyK')
    const sign = hash(fingerprint + reqtime + nonce + key).toString()
    const signSlice = sign.substr(10, 10)
    return $ajax
      .get(
        `${downloadAdUrl}/auth/download.json`,
        // 'https://20230712.oss-cn-hangzhou.aliyuncs.com/ad-v2.js',
        // 'https://20230712.oss-cn-hangzhou.aliyuncs.com/ad-encode-v3.txt',
        // 'https://20230712.oss-cn-hangzhou.aliyuncs.com/layer-visiblel.json',
        // 'https://20230712.oss-cn-hangzhou.aliyuncs.com/layer-visiblel-hidden.json',
        // 'https://20230712.oss-cn-hangzhou.aliyuncs.com/layer-visiblel-encode.txt',
        // 'https://20230712.oss-cn-hangzhou.aliyuncs.com/layer-visiblel-hidden-encode.txt',
        {
          // filename: 'layer-visiblel-encode.txt', // 不透明
          filename: 'layer-visiblel-hidden-encode.txt', // 透明
          appSource,
          ...extraData
        },
        {
          reqtime,
          nonce,
          fingerprint,
          sign: signSlice,
          auth: false,
          tag: 'direct'
        }
      )
      .then(res => {
        return utils.decrypt(res).toString()
      })
  }
}
